﻿using System.Data.Entity;
using XSTDZ.ERP.Core.Repositories;
using System.Threading;

namespace XSTDZ.ERP.EntityFramework
{
    public class EntityFrameworkRepositorContext : RepositoryContext,IEntityFrameworkRepositorContext 
    {
        private readonly ThreadLocal<DbContext> localContext = new ThreadLocal<DbContext>();
        public EntityFrameworkRepositorContext(DbContext efContext)
        {
            this.localContext.Value = efContext;
        }

        /// <summary>
        /// 注册一个删除聚合根到仓库上下文中
        /// </summary>
        /// <typeparam name="TAggregateRoot">指定的聚合根类型</typeparam>
        /// <param name="obj">聚合根实例</param>
        public override void RegisterDeleted<TAggregateRoot>(TAggregateRoot obj)
        {
            localContext.Value.Entry(obj).State = System.Data.EntityState.Deleted;
            IsCommited = false;
        }
        /// <summary>
        /// 注册一个修改聚合根到仓库上下文中.
        /// </summary>
        /// <typeparam name="TAggregateRoot">指定的聚合根类型</typeparam>
        /// <param name="obj">聚合根实例</param>
        public override void RegisterModified<TAggregateRoot>(TAggregateRoot obj)
        {
            localContext.Value.Entry(obj).State = System.Data.EntityState.Modified;
            IsCommited = false;
        }
        /// <summary>
        /// 册一个新增聚合根到仓库上下文中.
        /// </summary>
        /// <typeparam name="TAggregateRoot">指定的聚合根类型</typeparam>
        /// <param name="obj">聚合根实例</param>
        public override void RegisterNew<TAggregateRoot>(TAggregateRoot obj)
        {
            localContext.Value.Entry(obj).State = System.Data.EntityState.Added;
            IsCommited = false;
        }

        public DbContext Context
        {
            get { return localContext.Value; }
        }

        public override void Commit()
        {
            if (!IsCommited)
            {
                localContext.Value.SaveChanges();
                IsCommited = true;
            }
        }

        public override void Rollback()
        {
            IsCommited = false;
        }

        protected override void DisposeCore()
        {
            if (!IsCommited)
                Commit();
            localContext.Value.Dispose();
            localContext.Dispose();
            base.DisposeCore();
        }
    }
}
